<template>
    <MyDialog ref="myDialog" title="重置密码" width="480px" :on-confirm="confirm" :on-cancel="clearData">
        <MyForm ref="myForm" :form-data="formData" :form-item-list="formItemList" :form-rules="formRules"></MyForm>
    </MyDialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
interface FormData {
    id: string;
    password: string;
    confirmPassword: string;
}

const emit = defineEmits<{
    (event: 'complete', value: boolean): void;
}>();

const formData: FormData = {
    id: '',
    password: '',
    confirmPassword: '',
};

const formItemList: MyComment.FormItemProps<FormData>[] = [
    {
        prop: 'password',
        label: '密码',
        contentProps: { maxlength: 25, placeholder: '请输入8-25个字符', type: 'password', showPassword: true } as MyComment.FormItemContentProps['input'],
    },
    {
        prop: 'confirmPassword',
        label: '密码确认',
        contentProps: { maxlength: 25, placeholder: '请输入8-25个字符', type: 'password', showPassword: true } as MyComment.FormItemContentProps['input'],
    },
];

const confirmPasswordValidator = (_rule: any, value: string, callback: any) => {
    if (value && myForm.value) {
        if (value !== myForm.value.getData().password) {
            callback(new Error('两次密码输入不一致'));
        }
    }
    callback();
};

const formRules: MyComment.FormRules<FormData> = {
    password: [
        { required: true, trigger: 'blur', message: '请输入用户密码' },
        { min: 8, trigger: 'blur', message: '用户密码不能小于8个字符' },
    ],
    confirmPassword: [
        { required: true, trigger: 'blur', message: '请确认用户密码' },
        { validator: confirmPasswordValidator, trigger: 'blur', message: '两次密码输入不一致' },
    ],
};

const myDialog = ref<MyComment.DialogInstance>();
const myForm = ref<MyComment.FormInstance<FormData>>();

const confirm = async (): Promise<boolean> => {
    let result = (await myForm.value?.validate()) || false;
    if (result) {
        const data = myForm.value?.getData();
        if (data) {
            const submitData = {
                id: data.id,
                password: data.password,
            };
            const res = await MyService.account.resetPassword(submitData);
            if (res.code === 200) {
                emit('complete', true);
                return true;
            } else {
                ElMessage.error({
                    message: res.msg || '密码重置失败',
                });
                emit('complete', false);
                return false;
            }
        } else {
            emit('complete', false);
            return false;
        }
    }
    return result;
};

const open = (userId: string) => {
    formData.id = userId;
    myDialog.value?.open();
};

const clearData = () => {};

defineExpose({
    open,
});
</script>

<style scoped></style>
